/*
 * QueryDataFrame.java
 *
 * Created on Jan 4, 2012, 11:49:06 PM
 */
package gui;

import chart.QueryDataChartPanel;
import com.toedter.calendar.JDateChooser;
import com.toedter.calendar.JSpinnerDateEditor;

import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;

import db.DatabaseManager;
import db.entity.PadeLapse;
import db.entity.StationStatus;
import excelexporter.ExcelExporter;
import excelexporter.QueryDataBean;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.DefaultFontMapper;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;

import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import javax.swing.*;

import util.ErrorMessage;
import util.PropertiesLoader;
import util.SimpleFileFilter;

/**
 *
 * @author suzann
 */
public class QueryDataFrame extends javax.swing.JFrame {

    /** Creates new form QueryDataFrame */
    public QueryDataFrame() {
        //Variables initialisation
        dm = new DatabaseManager();
        qdcPnl = new QueryDataChartPanel();
        stationName = "01";
        sListStation = null;
        sListPadElapse = null;
        
        //Frame initialisation
        initComponents();
        setInitData();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jbtDisplay = new javax.swing.JButton();
        jbtExcel = new javax.swing.JButton();
        jdcFromDate = new JDateChooser(null, null, null, new JSpinnerDateEditor());
        jdcToDate = new JDateChooser(null, null, null, new JSpinnerDateEditor());
        dateFrom = new Date();
        sdmFrom = new SpinnerDateModel(dateFrom, null, null, 11);
        jspFromTime = new javax.swing.JSpinner(sdmFrom);
        dateTo = new Date();
        sdmTo = new SpinnerDateModel(dateTo, null, null, 11);
        jspToTime = new javax.swing.JSpinner(sdmTo);
        jPanel2 = new javax.swing.JPanel();
        jcbTemperature = new javax.swing.JCheckBox();
        jcbPadLife = new javax.swing.JCheckBox();
        jcbPressureR = new javax.swing.JCheckBox();
        jcbVacuumR = new javax.swing.JCheckBox();
        jcbVacuumL = new javax.swing.JCheckBox();
        jcbPressureL = new javax.swing.JCheckBox();
        jdlStation = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jbtPDF = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(1024, 688));

        jPanel1.setMinimumSize(new java.awt.Dimension(1024, 768));
        jPanel1.setPreferredSize(new java.awt.Dimension(571, 123));

        jLabel2.setText("From");

        jLabel3.setText("To");

        jbtDisplay.setText("Display");
        jbtDisplay.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtDisplayActionPerformed(evt);
            }
        });

        jbtExcel.setText("Export to Excel");
        jbtExcel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtExcelActionPerformed(evt);
            }
        });

        deFrom = new JSpinner.DateEditor(jspFromTime, "hh:mm a");
        jspFromTime.setEditor(deFrom);

        deTo = new JSpinner.DateEditor(jspToTime, "hh:mm a");
        jspToTime.setEditor(deTo);

        jcbTemperature.setText("Temperature");

        jcbPadLife.setText("Pad Life");

        jcbPressureR.setText("Pressure R");

        jcbVacuumR.setText("Vacuum R");

        jcbVacuumL.setText("Vacuum L");

        jcbPressureL.setText("Pressure L");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jcbTemperature)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jcbVacuumL)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jcbPressureL)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jcbPadLife)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jcbVacuumR)
                .addGap(2, 2, 2)
                .addComponent(jcbPressureR)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jcbTemperature)
                .addComponent(jcbVacuumL)
                .addComponent(jcbPressureL)
                .addComponent(jcbPadLife)
                .addComponent(jcbVacuumR)
                .addComponent(jcbPressureR))
        );

        jdlStation.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "01", "02", "03", "04", "05", "06", "07" }));

        jLabel1.setText("Station");

        jbtPDF.setText("Export to PDF");
        jbtPDF.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtPDFActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jdcFromDate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jdcToDate, javax.swing.GroupLayout.DEFAULT_SIZE, 182, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jspFromTime)
                            .addComponent(jspToTime, javax.swing.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbtDisplay)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbtExcel)
                        .addGap(6, 6, 6)
                        .addComponent(jbtPDF))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jdlStation, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(352, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jdlStation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(15, 15, 15)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jspFromTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jspToTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jdcFromDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel3)
                                .addComponent(jbtDisplay)
                                .addComponent(jbtExcel)
                                .addComponent(jbtPDF))
                            .addComponent(jdcToDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(20, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_END);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-1040)/2, (screenSize.height-726)/2, 1040, 726);
    }// </editor-fold>

    /****************************************************************************
     * Action Listeners
     ****************************************************************************/
    private void jbtExcelActionPerformed(java.awt.event.ActionEvent evt) {                                         
        exportToExcel();
    }                                        

    private void jbtDisplayActionPerformed(java.awt.event.ActionEvent evt) {                                           
        showQueryData();
    }                                          

    private void jbtPDFActionPerformed(java.awt.event.ActionEvent evt) {
        exportToPDF();
    }
    
     /****************************************************************************
     * Internal Operations
     ****************************************************************************/
    /**
     * This method sets the initial data for Query Data Chart Display at first launch.
     * @param 
     */
    private void setInitData()
    {
        //Set the initial Date
        Calendar today = Calendar.getInstance();        
        Calendar yesterday = Calendar.getInstance();
        yesterday.setTimeInMillis(today.getTimeInMillis() - 86400000L);        
        this.jdcToDate.setDate(today.getTime());
        this.jdcFromDate.setDate(yesterday.getTime());
        
        //set the initial selection of station
        jdlStation.setSelectedIndex(-1);
        jcbPadLife.setSelected(false);
        jcbPressureL.setSelected(false);
        jcbPressureR.setSelected(false);
        jcbTemperature.setSelected(false);
        jcbVacuumL.setSelected(false);
        jcbVacuumR.setSelected(false);
    
    }
    
     /**
     * Showing the Query Data
     * @param 
     */
    private void showQueryData()
    {
    	if(!(validateInput()))
    		return ;
    	
        /*get the inputs*/
        //1. Get the station name
        stationName = jdlStation.getSelectedItem().toString();
        System.out.println("Station Name: " + stationName);
        
        //2. From DateTime
        Calendar fromTime = Calendar.getInstance();
        fromTime.setTime(sdmFrom.getDate());
        Calendar fromDateTime = Calendar.getInstance();
        fromDateTime.setTime(jdcFromDate.getDate());        
        fromDateTime.set(11, fromTime.get(11));
        fromDateTime.set(12, fromTime.get(12));
        fromDateTime.set(13, fromTime.get(13));
        Date startDate = fromDateTime.getTime();
        System.out.println("From date =" + fromDateTime.getTime());

        //3. To DateTime
        Calendar toTime = Calendar.getInstance();
        toTime.setTime(sdmTo.getDate());
        Calendar toDateTime = Calendar.getInstance();
        toDateTime.setTime(jdcToDate.getDate());
        toDateTime.set(11, toTime.get(11));
        toDateTime.set(12, toTime.get(12));
        toDateTime.set(13, toTime.get(13));
        Date endDate = toDateTime.getTime();
        System.out.println("to date =" + toDateTime.getTime());
        
        
        sListPadElapse = dm.listPadElapseByStationNameDate(stationName,startDate, endDate);
        sListStation = dm.listStationStatusByStationNameDate(stationName, startDate, endDate);
        
        //4. Get the checkboxes: Determine which checkbox is ticked        
         if (jcbPadLife.isSelected() == true)
             qdcPnl.setPadLife(true);
         else
        	 qdcPnl.setPadLife(false);
         
         if (jcbPressureL.isSelected()   == true)
             qdcPnl.setPressureLeft(true);
         else
        	 qdcPnl.setPressureLeft(false);
         
         if (jcbPressureR.isSelected()   == true)
             qdcPnl.setPressureRight(true);
         else
        	 qdcPnl.setPressureRight(false);         
         
         if (jcbTemperature.isSelected() == true)
             qdcPnl.setTemperature(true);
         else
        	 qdcPnl.setTemperature(false);         
         
         if (jcbVacuumL.isSelected()     == true)
             qdcPnl.setVacuumLeft(true);
         else
        	 qdcPnl.setVacuumLeft(false);         
         
         if (jcbVacuumR.isSelected()     == true)
             qdcPnl.setVacuumRight(true);
         else
        	 qdcPnl.setVacuumRight(false);
         
         
        //Show the Chart
        qdcPnl.setVisible(true);
        qdcPnl.loadData("Polisher - Station "+stationName, sListStation, sListPadElapse);
        this.getContentPane().add(qdcPnl, java.awt.BorderLayout.CENTER);
        this.invalidate();
        this.validate();        
    }
    
    private boolean validateInput()
    {   
    	// VALIDATE STATION NUMBER
    	if(jdlStation.getSelectedItem() == null)
    	{
    		String errMsg = "Please select a Station Number.";
    		ErrorMessage.displayError(ErrorMessage.WARNING_ERROR, false, "Validation Error", errMsg);
    		return false;
    	}
    	
    	// VALIDATE BLANK FIELDS
    	boolean blankField = false;
    	String blankField_str = "";
    	if(jdcFromDate.getDate()==null)
    	{
    		blankField_str += "jdcFromDate;";
    		blankField = true;
    	}    	
    	if(jdcToDate.getDate()==null)
    	{
    		blankField_str += "jdcToDate;";
    		blankField = true;
    	}    	
    	
    	if(blankField)
    	{
    		String errMsg = "Please fill in the following field: \n" + blankField_str;
    		ErrorMessage.displayError(ErrorMessage.WARNING_ERROR, false, "Validation Error", errMsg);
    		return false;
    	}
    	
    	// VALIDATE FROM DATE BEFORE TO DATE
        Calendar fromTime = Calendar.getInstance();
        fromTime.setTime(sdmFrom.getDate());
        Calendar fromDateTime = Calendar.getInstance();
        fromDateTime.setTime(jdcFromDate.getDate());        
        fromDateTime.set(11, fromTime.get(11));
        fromDateTime.set(12, fromTime.get(12));
        fromDateTime.set(13, fromTime.get(13));
        Date startDate = fromDateTime.getTime();

        Calendar toTime = Calendar.getInstance();
        toTime.setTime(sdmTo.getDate());
        Calendar toDateTime = Calendar.getInstance();
        toDateTime.setTime(jdcToDate.getDate());
        toDateTime.set(11, toTime.get(11));
        toDateTime.set(12, toTime.get(12));
        toDateTime.set(13, toTime.get(13));
        Date endDate = toDateTime.getTime();
		
    	if(! startDate.before(endDate))
    	{
    		String errMsg = "From Date should be a date before To Date.";
    		ErrorMessage.displayError(ErrorMessage.WARNING_ERROR, false, "Validation Error", errMsg);
    		return false;
    	}
    	
    	//Validate Data Selection
    	if(!jcbPadLife.isSelected() && !jcbPressureL.isSelected() && !jcbPressureR.isSelected() && !jcbTemperature.isSelected() && !jcbVacuumL.isSelected() && !jcbVacuumR.isSelected())
    	{
    		String errMsg = "Please select at least 1 data type.";
    		ErrorMessage.displayError(ErrorMessage.WARNING_ERROR, false, "Validation Error", errMsg);
    		return false;
    	}
    	
    	// Difference between From Data and To Date should be within range in properties file
    	int difference = toDateTime.get(Calendar.DAY_OF_YEAR) - fromDateTime.get(Calendar.DAY_OF_YEAR);
    	
    	if (difference > PropertiesLoader.getQueryDataMaxRange())
    	{
    		String errMsg = "To Date cannot be "+PropertiesLoader.getQueryDataMaxRange()+" days after From Date.";
    		ErrorMessage.displayError(ErrorMessage.WARNING_ERROR, false, "Validation Error", errMsg);
    		return false;
    	}    	
    	
    	return true;
    }
    
    private void exportToExcel()
    {
    	if(!(validateInput()))
    		return ;
    	
        /*get the inputs*/
        //1. Get the station name
        stationName = jdlStation.getSelectedItem().toString();
        System.out.println("Station Name: " + stationName);
        
        //2. From DateTime
        Calendar fromTime = Calendar.getInstance();
        fromTime.setTime(sdmFrom.getDate());
        Calendar fromDateTime = Calendar.getInstance();
        fromDateTime.setTime(jdcFromDate.getDate());        
        fromDateTime.set(11, fromTime.get(11));
        fromDateTime.set(12, fromTime.get(12));
        fromDateTime.set(13, fromTime.get(13));
        Date startDate = fromDateTime.getTime();
        System.out.println("From date =" + fromDateTime.getTime());

        //3. To DateTime
        Calendar toTime = Calendar.getInstance();
        toTime.setTime(sdmTo.getDate());
        Calendar toDateTime = Calendar.getInstance();
        toDateTime.setTime(jdcToDate.getDate());
        toDateTime.set(11, toTime.get(11));
        toDateTime.set(12, toTime.get(12));
        toDateTime.set(13, toTime.get(13));
        Date endDate = toDateTime.getTime();
        System.out.println("to date =" + toDateTime.getTime());
                
        sListPadElapse = dm.listPadElapseByStationNameDate(stationName,startDate, endDate);
        sListStation = dm.listStationStatusByStationNameDate(stationName, startDate, endDate);
                        
        // Generate Pad Life (Elapse) data
        List<PadeLapse> pList = (List<PadeLapse>) sListPadElapse;
        List<DateElapseClass> dateElapseLS = new ArrayList<DateElapseClass>();
    	
    	if(pList.size()!=0){				
			DatabaseManager db = new DatabaseManager();
			// Calculate elapse hour for 1st padeLapse object
			List<PadeLapse> pList2 = db.listPadElapseOfPadID(pList.get(0).getId().getPadID());
			long elapse = 0L;
			Date pDate = pList.get(0).getId().getStartTime();
			for(PadeLapse pItem2 : pList2)
			{
				if(pItem2.getId().getStartTime().equals(pDate))
					break;
				
				elapse += pItem2.getElapseTimeMillis();
			}
			dateElapseLS.add(new DateElapseClass(pDate, elapse/3600000.0));
						
			// Get elapse for the remaining padeLapse Object
			String currPadID = pList.get(0).getId().getPadID();
			for(int i=1; i<pList.size(); i++)
			{	
				PadeLapse pItem = pList.get(i);
				if(! pItem.getId().getPadID().equals(currPadID))
				{
					elapse = 0L;
					currPadID = pItem.getId().getPadID();
				}
				dateElapseLS.add(new DateElapseClass(pItem.getId().getStartTime(), elapse/3600000.0));
				elapse += pItem.getElapseTimeMillis();

				dateElapseLS.add(new DateElapseClass(pItem.getEndTime(), elapse/3600000.0));
			}
		}
        
    	Collections.sort(dateElapseLS);
    	Collections.sort(sListStation, new StationStatusComparator());
    	
    	// Fill Bean data    	
        ArrayList<QueryDataBean> beanLS = new ArrayList<QueryDataBean>();
        int dateElapseIndex = 0;
        DateElapseClass dateElapseItem = dateElapseLS.get(dateElapseIndex);
        
        for(Object sItem_obj : sListStation)
		{
        	if(!(sItem_obj instanceof StationStatus))
        		continue ;
        	StationStatus statusItem = (StationStatus)sItem_obj;
        	
        	double temperature = statusItem.getTemperature();
        	Float pressureLeft = statusItem.getPressureLeft();
        	Float pressureRight = statusItem.getPressureRight();
        	Float vacuumLeft = statusItem.getVacuumLeft();
        	Float vacuumRight = statusItem.getVacuumRight();
        	
        	QueryDataBean bean = new QueryDataBean();
        	bean.setDateTme(statusItem.getId().getDataDate());
        	bean.setStation(statusItem.getId().getName());
        	bean.setPressureLeft(pressureLeft);
        	bean.setPressureRight(pressureRight);
        	bean.setTemperature(temperature);
        	bean.setVacuumLeft(vacuumLeft);
        	bean.setVacuuumRight(vacuumRight);
        	        		    
        	// Get Pad Life (elapse) data
        	while(statusItem.getId().getDataDate().after(dateElapseItem.getItemDate()))
        	{
        		dateElapseIndex++;
        		if(dateElapseIndex > dateElapseLS.size()-1)        			
        			break;
        		
        		dateElapseItem = dateElapseLS.get(dateElapseIndex);
        	}

        	double elapse = dateElapseItem.getItemElapse();
        	bean.setPadLife(elapse);   
        	beanLS.add(bean);
		}
        
        int i=0;
        for(QueryDataBean bean : beanLS)
        {
        	System.out.print(bean.getStation()+", ");
        	System.out.print(bean.getDateTme()+", ");
        	System.out.print(bean.getTemperature()+", ");
        	System.out.print(bean.getVacuumLeft()+", ");
        	System.out.print(bean.getVacuuumRight()+", ");
        	System.out.print(bean.getPressureLeft()+", ");
        	System.out.print(bean.getPressureRight()+", ");
        	System.out.print(bean.getPadLife()+", ");
        	System.out.println();
        	i++;
        	if(i>15)
        		break;
        }
        
        new ExcelExporter().generateQueryDataExcel(beanLS);
    }
    
    private class StationStatusComparator implements Comparator
    {
		public int compare(Object arg0, Object arg1) {
			if(arg0 instanceof StationStatus && arg1 instanceof StationStatus)
				return compare((StationStatus)arg0, (StationStatus)arg1);
			
			return 0;
		}
    	
		public int compare(StationStatus arg0, StationStatus arg1)
		{
			return arg0.getId().getDataDate().compareTo(arg1.getId().getDataDate());
		}
    }
    
    private class DateElapseClass implements Comparable
    {
    	Date itemDate;
    	double itemElapse;
    	
    	public DateElapseClass(Date itemDate, double itemElapse)
    	{
    		this.itemDate = itemDate;
    		this.itemElapse = itemElapse;
    	}

		public int compareTo(DateElapseClass arg0) {
			return itemDate.compareTo(arg0.itemDate);
		}

		public int compareTo(Object o) {
			if(o instanceof DateElapseClass)
				return compareTo((DateElapseClass)o);			
			return -1;
		}  	
		
		public Date getItemDate()
		{
			return itemDate;
		}
		
		public double getItemElapse()
		{
			return itemElapse;
		}
    }
    
    private void exportToPDF() {
    	JFileChooser fc = new JFileChooser();
    	fc.setFileSelectionMode(0);
    	fc.setFileFilter(new SimpleFileFilter("pdf"));
    	
    	int returnVal = fc.showSaveDialog(this);
    	if (returnVal == 0) {
    		File file = fc.getSelectedFile();
    		
    		String path = file.getAbsolutePath();
    		
    		if (!path.endsWith(".pdf")) {
    		path = path + ".pdf";
    		}
    		
    		String finalPath = path;
    		try {
    			OutputStream out = new BufferedOutputStream(new FileOutputStream(new File(finalPath)));
    			Rectangle pagesize = new Rectangle(842, 595);
    			Document document = new Document(pagesize, 50.0F, 50.0F, 50.0F, 50.0F);
    			try {
    				PdfWriter writer = PdfWriter.getInstance(document, out);
    				document.addAuthor("JFreeChart");
    				document.addSubject("Demonstration");
    				document.open();
    				PdfContentByte cb = writer.getDirectContent();
    				PdfTemplate tp = cb.createTemplate(842, 595);
    				Graphics2D g2 = tp.createGraphics(842, 595, new DefaultFontMapper());
    				Rectangle2D r2D = new Rectangle2D.Double(0.0D, 0.0D, 842, 595);

    				qdcPnl.drawChart(g2, r2D);

    				g2.dispose();
    				cb.addTemplate(tp, 0.0F, 0.0F);
    			} catch (DocumentException de) {
    				System.err.println(de.getMessage());
    			}
    			document.close();
    			out.close();
    			
    			JOptionPane.showMessageDialog(null, "Graph successfully exported to PDF.", "Export Successfully", JOptionPane.PLAIN_MESSAGE);
    		}
    		catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }

    
    public void addNotify() {
        super.addNotify();
        // Buffer
        createBufferStrategy(2);           
        //BufferStrategy strategy = getBufferStrategy();
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(QueryDataFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(QueryDataFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(QueryDataFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(QueryDataFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new QueryDataFrame().setVisible(true);
            }
        });
    }
    /****************************************************************************
     * INTERNAL OPERATIONS : THE FRAME
     ****************************************************************************/
    
    /**
     * Prompts up a confirmation dialog to confirm the exit action.
     * Upon confirmation, dispose the frame.
     */
    private void onExit()
    {
    	//remove the chart panel
        qdcPnl.setVisible(false);
        this.invalidate();
        this.validate();
        
        //reset all the values to default
        setInitData();
        
        //dispose the frame
        this.dispose();
    }
    
    /**
     * This is a hack for user to click on the 'x' button on window
     */
    protected void processWindowEvent(WindowEvent we)
    {
            if(we.getID() == WindowEvent.WINDOW_CLOSING)
                    onExit();
    }
    /****************************************************************************
     *  THE VARIABLES
     ****************************************************************************/
    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JButton jbtDisplay;
    private javax.swing.JButton jbtExcel;
    private javax.swing.JButton jbtPDF;
    private javax.swing.JCheckBox jcbPadLife;
    private javax.swing.JCheckBox jcbPressureL;
    private javax.swing.JCheckBox jcbPressureR;
    private javax.swing.JCheckBox jcbTemperature;
    private javax.swing.JCheckBox jcbVacuumL;
    private javax.swing.JCheckBox jcbVacuumR;
    private com.toedter.calendar.JDateChooser jdcFromDate;
    private com.toedter.calendar.JDateChooser jdcToDate;
    private javax.swing.JComboBox jdlStation;
    Date dateFrom;
    SpinnerDateModel sdmFrom;
    JSpinner.DateEditor deFrom;
    private javax.swing.JSpinner jspFromTime;
    Date dateTo;
    SpinnerDateModel sdmTo;
    JSpinner.DateEditor deTo;
    private javax.swing.JSpinner jspToTime;
    // End of variables declaration
    private DatabaseManager dm;
    private QueryDataChartPanel qdcPnl;
    private String stationName;
    private List sListStation;
    private List sListPadElapse;
}
